package org.ccahouse.ccatrain.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.ccahouse.ccacommons.common.RestResult;
import org.ccahouse.ccacommons.common.ResultUtils;
import org.ccahouse.ccatrain.dto.AuthUserDto;
import org.ccahouse.ccatrain.entity.Audience;
import org.ccahouse.ccatrain.entity.AuthUser;
import org.ccahouse.ccatrain.mapper.AuthUserMapper;
import org.ccahouse.ccatrain.service.IAuthService;
import org.ccahouse.ccatrain.util.JwtTokenUtil;
import org.ccahouse.ccatrain.vo.AuthUserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class AuthServiceImpl extends ServiceImpl<AuthUserMapper, AuthUser> implements IAuthService {

    @Autowired
    private Audience audience;

    @Override
    public RestResult register(AuthUserDto authUserDto) {
        AuthUser authUser = this.getOne(new QueryWrapper<AuthUser>()
                .lambda()
                .eq(AuthUser::getUsername, authUserDto.getUsername())
        );
        if (authUser != null) {
            return ResultUtils.error("该账户已注册,请重试");
        }
        authUser = new AuthUser();
        BeanUtils.copyProperties(authUserDto, authUser);
        authUser.setPassword(JwtTokenUtil.md5(authUser.getPassword()));
        boolean re = this.save(authUser);
        if (!re) {
            return ResultUtils.error("注册失败");
        }
        return ResultUtils.success("注册成功", formatTokenInfo(authUser));
    }

    @Override
    public RestResult login(String username, String password) {
        AuthUser authUser = this.getOne(new QueryWrapper<AuthUser>()
                .lambda()
                .eq(AuthUser::getUsername, username)
                .eq(AuthUser::getPassword, JwtTokenUtil.md5(password))
        );
        if (authUser == null) {
            return ResultUtils.error("账号或密码错误");
        }
        return ResultUtils.success("登录成功", formatTokenInfo(authUser));
    }

    private HashMap<String, Object> formatTokenInfo(AuthUser authUser){
        String token = JwtTokenUtil.createJwt(authUser.getId(), authUser.getUsername(), audience);
        HashMap<String, Object> info = new HashMap<>();
        AuthUserVo authUserVo = new AuthUserVo();
        BeanUtils.copyProperties(authUser, authUserVo);
        info.put("token", token);
        info.put("userInfo", authUserVo);
        return info;
    }
}
